/**
 * Copyright (c) 2015-2017, Henry Yang 杨勇 (gismail@foxmail.com).
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.lambkit.web.validator;

import cn.hutool.core.util.StrUtil;
import com.jfinal.core.Controller;
import com.jfinal.validate.Validator;
import com.lambkit.db.mgr.*;
import com.lambkit.JFLambkit;
import com.lambkit.web.ControllerContext;

import java.util.List;

public abstract class LambkitValidator extends Validator {

	@Override
	protected void validate(Controller controller) {
		ControllerContext controllerContext = new ControllerContext(controller);
		if(!isValidate(controllerContext)) {
			return;
		}
		setShortCircuit(true);
		
		MgrTable tbc = getBase(controllerContext);
		if (tbc == null) {
			if(isUseMgrTable()) {
				addError("msg", "config info is null");
				return;
			}
		}

		if(tbc!=null && isUseMgrTable()) {
			String prefix = getPrefix(controllerContext);
			prefix = prefix == null ? "model." : prefix + ".";

			List<? extends IField> flds = tbc.getFieldList();
			for(int i=0; i<flds.size(); i++) {
				IField fld = flds.get(i);
				String value = controller.getPara(prefix+fld.getName());
				String valueStr = StrUtil.isBlank(value) ? "--" : value;
				System.out.print("[column]:"+fld.getName()+", [value]:" + valueStr);
				System.out.println(", [isEdit]:"+fld.getIsedit()+
						", [isMust]:"+fld.getIsmustfld()+
						", [isKey]:"+fld.getIskey());
				if(fld.getIsedit().equals("N") ||
						fld.getIsmustfld().equals("N") ||
						fld.getIskey().equals("Y")) {
					if(!StrUtil.isNotBlank(value)){
						//System.out.println("continue");
						continue;
					}
				}
				if(fld.getDatatype().startsWith("float ") || fld.getDatatype().startsWith("double ")
						|| fld.getDatatype().startsWith("number ") || fld.getDatatype().startsWith("numeric ")
						|| fld.getDatatype().startsWith("decimal ")) {
					validateDouble(prefix+fld.getName(), "msg_"+fld.getName(), "请您输入"+fld.getTitle()+"!并且是数字!");
				} else if(fld.getDatatype().startsWith("int ") || fld.getDatatype().startsWith("smallint ") ||
						fld.getDatatype().startsWith("tinyint ")) {
					validateInteger(prefix+fld.getName(), "msg_"+fld.getName(), "请您输入"+fld.getTitle()+"!并且是整数!");
				} else if(fld.getDatatype().startsWith("long ") || fld.getDatatype().startsWith("bigint ")) {
					validateLong(prefix+fld.getName(), "msg_"+fld.getName(), "请您输入"+fld.getTitle()+"!并且是整数!");
				} else if(fld.getDatatype().startsWith("date")) {
					validateDate(prefix+fld.getName(), "msg_"+fld.getName(), "请您输入"+fld.getTitle()+"!并且是日期!");
				} else {
					validateRequired(prefix+fld.getName(), "msg_"+fld.getName(), "请您输入"+fld.getTitle()+"!");
				}
			}
		}

		validateExt(controllerContext);
	}

	@Override
	protected void handleError(Controller controller) {
		if(controller.getPara("at")!=null && !controller.getPara("at").equalsIgnoreCase("json")) {
			controller.keepPara();
			controller.setAttr("token", "1");
			controller.render(controller.getPara("at"));
		} else {
			controller.setAttr("code", 0);
			controller.setAttr("error", true);
			controller.setAttr("message", "验证失败");
			controller.renderJson();
		}
	}
	
	protected MgrTable getBase(ControllerContext controller) {
		String tbname = getTableName(controller);
		if(StrUtil.isNotBlank(tbname)) {
			MgrdbService tcs = JFLambkit.getApp().getBean(MgrdbService.class);
			MgrTable tbc = tcs!=null ? tcs.createTable(tbname, MgrConstants.EDIT) : null;
			if(tbc!=null) {
				if(tbc.getModel()!=null) {
					controller.setAttr("tag", tbc.getModel().getId());
				}
				controller.setAttr("mgrdb", tbc);
			}
			return tbc;
		}
		return null;
	}
	
	/**
	 * 获取表格id
	 * @param controller
	 * @return
	 */
	protected abstract String getTableName(ControllerContext controller);
	
	/**
	 * 获取表单前缀
	 * @return
	 */
	protected String getPrefix(ControllerContext controller) {
		String prefix = controller.getAttr("prefix");
		prefix = StrUtil.isBlank(prefix) ? getPrefix() : prefix;
		prefix = StrUtil.isBlank(prefix) ? "model" : prefix;
		return prefix;
	}

	protected String getPrefix() { return null;}

		/**
         * 自定义验证扩展
         * @param controller
         */
	protected void validateExt(ControllerContext controller) {
	}
	
	/**
	 * 是否开启验证
	 * @return
	 */
	protected boolean isValidate(ControllerContext controller) {
		return controller.isPOST() ? true : false;
	}

	/**
	 * 验证是否需要mgrtable
	 * @return
	 */
	protected boolean isUseMgrTable() {
		return true;
	}
}
